package com.cscec81.passport.base.cas.configuration;

import lombok.Getter;
import lombok.Setter;
import org.jasig.cas.client.util.CommonUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.cas.ServiceProperties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.util.Assert;

@Getter
@Setter
public class CasAuthenticationEntryPoint implements AuthenticationEntryPoint, InitializingBean {
  private ServiceProperties serviceProperties;
  private String loginUrl;
  private boolean encodeServiceUrlWithSessionId = true;

  public final void commence(HttpServletRequest servletRequest, HttpServletResponse response, AuthenticationException authenticationException) throws IOException {
    String urlEncodedService = this.createServiceUrl(servletRequest, response);
    String redirectUrl = this.createRedirectUrl(urlEncodedService);
    // 返回401
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    PrintWriter out = response.getWriter();
    // 返回与前端约定的格式，前端能获取到redirectUrl跳转即可
    out.write("{\"redirectUrl\":" + "\"" + redirectUrl + "\"" + "}");
  }

  @Override
  public void afterPropertiesSet() throws Exception {
    Assert.hasLength(this.loginUrl, "loginUrl must be specified");
    Assert.notNull(this.serviceProperties, "serviceProperties must be specified");
    Assert.notNull(this.serviceProperties.getService(), "serviceProperties.getService() cannot be null.");
  }

  protected String createRedirectUrl(String serviceUrl) {
    return CommonUtils.constructRedirectUrl(this.loginUrl, this.serviceProperties.getServiceParameter(), serviceUrl, this.serviceProperties.isSendRenew(), false);
  }

  protected String createServiceUrl(HttpServletRequest request, HttpServletResponse response) {
    return CommonUtils.constructServiceUrl((HttpServletRequest)null, response, this.serviceProperties.getService(), (String)null, this.serviceProperties.getArtifactParameter(), this.encodeServiceUrlWithSessionId);
  }
}
